package g.beny.framework.validation;

import g.beny.framework.exception.ArgsException;
import g.beny.framework.validation.annotation.AnnotationValidation;

import org.nutz.aop.InterceptorChain;
import org.nutz.aop.MethodInterceptor;

/**
 * 基于注解的验证用拦截器
 * <p>
 * 该拦截器主要用于方法参数的验证，要求该方法中必须有一个 Errors 类型的参数(允许为空)，当验证完成后会向这个参数赋值
 * 
 */
public class ValidationInterceptor implements MethodInterceptor {

	private static AnnotationValidation av = new AnnotationValidation();

	@Override
	public void filter(InterceptorChain chain) throws Throwable {
		Errors es = ValidationUtils.checkArgs(chain.getCallingMethod().getParameterTypes(), chain.getArgs());
		if (null != es) {
			for (Object argsObj : chain.getArgs()) {
				if (argsObj instanceof Errors)
					continue;
				av.validate(argsObj, es);
			}
		}
		
		if(es.hasError()){
			throw new ArgsException(es.getErrorsList());
		}else{
			chain.doChain();
		}
	}
}
